<?php
/**
 * Created by PhpStorm.
 * User: bevan
 * Date: 2018/1/12
 * Time: 下午4:41
 */

namespace app\open\controller;

use function GuzzleHttp\Psr7\build_query;
use think\Controller;
use think\Db;
use think\facade\Hook;

/**
 * 公开上传类，任何人都可以上传
 */
class UploadController extends Controller
{
    public $options;
    protected $uid = 0;

    public function __construct()
    {
        parent::__construct();
        $login_msg = cmf_is_login();
        if ($login_msg['code'] != '1001') {
            $this->options = cmf_option('publicupload');
            if (!$this->options['upload_status']) {
                if (request()->isAjax()) {
                    $this->result('', 4001, '未开放公共上传，请先登录', 'json');

                } else {
                    $this->error('未开放公共上传，请先登录', '', '', '-1');
                }
            }
        } else {
            $this->uid = $login_msg['data']['uid'];
            $this->options = cmf_option('upload');
        }
        $this->options['url'] = '/open/upload/image';
        $this->options['domain'] = '';
        //默认上传参数
        //钩子修改options
        //第三方上传post参数给options的posts下的数组，post需要http_build_query
        $res = hook_one('upload_options', $this->options);
        if ($res) {
            $this->options = $res;
        }
    }

    /**
     * 适用于cdn上传，默认加载后台配置，有钩子可以增加选项。此处适用于ajax获取配置
     */
    public function options()
    {
        $this->result($this->options, 1001, '获取成功', 'json');
    }

    /**
     * 图片上传
     */
    public function image()
    {
        $file = request()->file('file');
        if (!$file) {
            return $this->result('', 4001, '请先选择文件', 'json');
        }
        if ($this->options['upload_img_size'] != 0) {
            $map['size'] = $this->options['upload_img_size'] * 1024;
        }
        if ($this->options['upload_img_ext']) {
            $map['ext'] = $this->options['upload_img_ext'];
        }
        if (!empty($map)) {
            $info = $file->validate($map)->move('./static/upload/images/');
        } else {
            $info = $file->move('./static/upload/images/');
        }
        if ($this->options['upload_img_water_status']) {
            $image = \think\Image::open('./static/upload/images/' . $info->getSaveName());
            if (!$this->ptions['upload_img_water_position']) {
                $this->options['upload_img_water_position'] = 1;
            }
            if ($this->options['upload_img_water_alpha'] == '') {
                $this->options['upload_img_water_alpha'] = '0';
            }
            if ($this->options['upload_img_water_img'] != '') {
                $image->water(BASE_ROOT . '/public' . $this->options['upload_img_water_img'], $this->options['upload_img_water_position'], $this->options['upload_img_water_alpha'])->save('./static/upload/images/' . $info->getSaveName());
            }
        }
        if ($info) {
            $id = $this->record($info, 'image', '/static/upload/images/');
            hook_one('open_upload_image_end', $info);
            return json(['d_id' => $id, 'path' => '/static/upload/images/' . $info->getSaveName()]);
        } else {
            // 上传失败获取错误信息
            return json(['msg' => $file->getError()], 401);
        }
    }

    protected function record($info, $type = '', $path = '')
    {
        $data['gid'] = request()->post('gid') ?: 0;
        if ($data['gid'] <= 0) {
            $data['gid'] = 0;
        }
        $map['id'] = $data['gid'];
        $map['uid'] = cmf_get_uid();
        $group = Db::name('upload_group')->where($map)->find();
        if (!$group || $group['type'] != $type) {
            $group = 0;
        }
        $data['uid'] = $this->uid;
        $data['filename'] = $info->getInfo('name');
        $data['extension'] = $info->getExtension();
        $data['file_size'] = $info->getInfo('size');
        $data['file_path'] = $path . $info->getSaveName();
        $data['file_md5'] = $info->md5();
        $data['d_id'] = md5($info->hash() . time());
        $data['file_type'] = $type;
        $data['file_mime'] = $info->getInfo('type');
        $data['create_time'] = time();
        Db::name('upload_file')->insertGetId($data);
        return $data['d_id'];
    }

    /**
     * 文件上传
     */
    public function file()
    {
        $file = request()->file('file');
        if (!$file) {
            return $this->result('', 4001, '请先选择文件', 'json');
        }
        if ($this->options['upload_file_size'] != 0) {
            $map['size'] = $this->options['upload_file_size'] * 1024;
        }
        if ($this->options['upload_file_ext']) {
            $map['ext'] = $this->options['upload_file_ext'];
        }
        if (!empty($map)) {
            $info = $file->validate($map)->move('./static/upload/files/');
        } else {
            $info = $file->move('./static/upload/files/');
        }
        if ($info) {
            $id = $this->record($info, 'file', '/static/upload/files/');
            hook_one('open_upload_file_end', $info);
            return json(['d_id' => $id, 'path' => '/static/upload/files/' . $info->getSaveName()]);
        } else {
            // 上传失败获取错误信息
            return json(['msg' => $file->getError()], 401);
        }
    }
}
